/**  
 * @Title:  DataSourceController.java   
 * @Package com.gtjy.p2p.modules.sys.controllers   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: 吴元森 
 * @date:   2018年7月19日 下午6:36:03   
 * @version V1.0 
 * @Copyright: 2018 吴元森.
 */
package com.platform.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.base.R;
import com.platform.base.mvc.BaseController;
import com.platform.dto.DataSource;
import com.platform.entity.ExcelColumns;
import com.platform.ext.offices.poi.excel.ExcelUtil;
import com.platform.ext.offices.poi.utils.DownLoadUtil;
import com.platform.logger.annotation.ApiLog;
import com.platform.service.IDataSource;
import com.platform.utils.HttpContextUtils;
import com.platform.utils.JDBCUtil;
import com.platform.utils.TokenManager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;


/**   
 * @ClassName:  DataSourceController   
 * @Description: 数据源管理
 * @author: 吴元森 
 * @date:   2018年7月19日 下午6:36:03   
 *     
 * @Copyright: 2018 吴元森.  
 */
@Controller
@RequestMapping("/dataSource") 
@Api(tags="COMMON-数据源管理")
public class DataSourceController  extends BaseController{
	
	@Autowired
	private IDataSource dataSourceServices;
	
	@RequestMapping(value="data",method=RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="分页查询")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ds", value = "数据对象", required = true, dataType = "DataSouce"),
        @ApiImplicitParam(name = "start", value = "页码", required = true, dataType = "int"),
        @ApiImplicitParam(name = "limit", value = "每页显示条数", required = true, dataType = "int")
	})
	public Object selectAll(DataSource ds,
			Integer start,
			Integer limit,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {
		return dataSourceServices.findByPaging(start, limit, ds);
	}
	
    @RequestMapping(value="get",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取单条信息")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "code", value = "数据主键", required = true, dataType = "String"),
	})
	public Object get(long code,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {
		return R.success(dataSourceServices.selectById(code));
	}
	
    @RequestMapping(value="browse/leftTree",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取数据源列表提供给tree组件使用")
	public Object selectDataSoucesByTree(HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
		return dataSourceServices.selectDataSoucesByTree(null).getData();
	}
	
    @RequestMapping(value="remove",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="删除数据")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ids", value = "数据编号，多个逗号（,）分隔", required = true, dataType = "String")
	})
    @ApiLog(value = "删除数据源",desc = "删除数据源")
	public Object remove(String ids,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
		return dataSourceServices.deleteByCode(ids);
	}
	
    @RequestMapping(value="add",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="新增数据")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ds", value = "数据源对象", required = true, dataType = "DataSource")
	})
    @ApiLog(value="新增数据源",desc = "新增数据源")
	public Object add(DataSource ds,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	ds.setCreater(TokenManager.getUserName(HttpContextUtils.getAccessToken()));
		ds.setCreateDate(new Date());
		return dataSourceServices.insertDs(ds);
	}
	
    @RequestMapping(value="modify",method=RequestMethod.POST)
    @ApiLog(value = "修改修改数据源",desc = "修改修改数据源")
    @ResponseBody
    @ApiOperation(value="修改数据")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ds", value = "数据源对象", required = true, dataType = "DataSource")
	})
	public Object modify(DataSource ds,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	ds.setLastModifier(TokenManager.getUserName(HttpContextUtils.getAccessToken()));
		ds.setLastModifyDate(new Date());
		return dataSourceServices.modifyDs(ds);
	}
    
    @RequestMapping(value="testConnection",method= {RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="测试数据库连接是否正常")
    @ResponseBody
	public Object testConnection(DataSource ds) {
    	if(ds.getDataBaseType().equalsIgnoreCase("FTP")) {
			return R.fail("系统暂不支持此类型的服务测试，请自行确保地址正常");
    	}else {
    		String driverName = ds.getDriverClassName();
			String jdbcUrl = JDBCUtil.buildDBConnectStr(ds.getDataBaseType(),ds.getIpAddress(),ds.getPortNumber(),ds.getDefaultSchema());
			String userName = ds.getUserName();
			String pwd =  ds.getPassword();
			Connection conn = JDBCUtil.createTempConnection(driverName, jdbcUrl, userName, pwd);
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return R.success();
			}else {
				return R.fail();
			}
    	}
	}
	
	@RequestMapping(value = "/export",method = {RequestMethod.GET,RequestMethod.POST})
	public void exportToExcel(@RequestParam Map<String,Object> params)  throws IOException{
		//参数解析
		List<ExcelColumns> columns = JSONUtil.parseArray(params.get("columns").toString()).toList(ExcelColumns.class);
		boolean isPDF = params.get("toPdf") != null?Boolean.parseBoolean(params.get("toPdf").toString()):false;	//是否导出当前页
		String protalParamsStr = params.get("protalParams").toString();
		@SuppressWarnings("unchecked")
		Map<String,Object> protalParams = JSONUtil.toBean(protalParamsStr, Map.class);
	    boolean colorless 	= Boolean.parseBoolean(params.get("colorless").toString());
	    boolean usemonetary = Boolean.parseBoolean(params.get("usemonetary").toString());
	    boolean sumless 	= Boolean.parseBoolean(params.get("sumless").toString());
	    boolean splitCell 	= Boolean.parseBoolean(params.get("splitCell").toString());
	    boolean watermark 	= Boolean.parseBoolean(params.get("watermark").toString());
	    String openPassword = params.get("openPassword").toString();
	    String userName		= params.get("userName").toString();
	    String deptname		= params.get("deptname").toString();
	    String systemName	= params.get("systemName").toString();
	    String modularName = params.get("modularText").toString();
		//生成
		int start = Integer.valueOf(params.get("currentPage").toString());
		int limit = Integer.valueOf(params.get("pageSize").toString());
	    @SuppressWarnings("unchecked")
		List<DataSource> exportData = (List<DataSource>)dataSourceServices.findByPaging(start,limit,BeanUtil.fillBeanWithMap(protalParams, new DataSource(), true)).getData();
		OutputStream osExcel = ExcelUtil.generateExcelOrPDF(modularName,exportData,protalParams,columns,colorless,usemonetary,sumless,splitCell,watermark,openPassword,userName,deptname,systemName);
		if(isPDF) {
			OutputStream osPDF = DownLoadUtil.excelStreamToPDFStream(new ByteArrayInputStream(((ByteArrayOutputStream) osExcel).toByteArray()));
			String fn = modularName + "列表.pdf";
			download(osPDF, fn, response);
		}else {
			String fn = modularName + "列表.xls";
			download(osExcel, fn, response);
		}
	}
	
}
